package com.craftworks.ui;

import oshi.hardware.NetworkIF;

import javax.swing.*;
import java.awt.*;

public class NetworkIFListRenderer extends JPanel implements ListCellRenderer<NetworkIF>
{
    private JLabel nameLabel;
    private JLabel addressLabel;

    public NetworkIFListRenderer()
    {
        setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

        nameLabel = new JLabel();
        nameLabel.setText("未知网络接口");
        nameLabel.setFont(new Font(Font.SERIF, Font.BOLD, 16));
        addressLabel = new JLabel();
        addressLabel.setText("127.0.0.1");
        addressLabel.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
    }

    @Override
    public Component getListCellRendererComponent(JList<? extends NetworkIF> list,
                                                  NetworkIF nif,
                                                  int index,
                                                  boolean isSelected,
                                                  boolean cellHasFocus)
    {
        if (isSelected)
        {
            setBackground(list.getSelectionBackground());
            setForeground(list.getSelectionForeground());
        } else
        {
            setBackground(list.getBackground());
            setForeground(list.getForeground());
        }

        nameLabel.setText(String.format("%s - %s", nif.getIfAlias(), nif.getDisplayName()));
        addressLabel.setText(nif.getIPv4addr()[0]);

        remove(nameLabel);
        remove(addressLabel);

        // ComboBox的内容条的索引是-1，下拉列表的内容索引是0~n。
        // 所以可以通过索引来判断显示位置，从而调整显示的Component。
        if (index == -1)
        {
            add(nameLabel);
        } else
        {
            add(nameLabel);
            add(addressLabel);
        }

        return this;
    }
}
